package com.eric.study.reactor.controller;

import com.eric.study.reactor.commons.ConstantsFields;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * <p> ContextTestController.
 *
 * <p>
 * change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2023/9/15    ********     Qiheng Zhang    create file.
 * </pre>
 *
 * @author Qiheng Zhang
 * @date 2023/9/15 11:21
 * @copyright 2023, FA Software (Shanghai) Co., Ltd. All Rights Reserved.
 * @since 1.0.0
 */
@RestController
@Slf4j
public class ContextTestController {

    @RequestMapping("hi/{name}")
    public Mono<String> save(@PathVariable("name") String name) {

        log.info("接收参数：{}", name);

        return Mono.deferContextual(ctx -> {
            log.info("接收 traceId = {}", ctx.getOrEmpty(ConstantsFields.TRACE_ID));
            return Mono.fromSupplier(() -> "hi, " + name);
        });
    }

    @PostMapping("/sync")
    public String sync() {
        log.info("sync method start");
        String result = this.execute();
        log.info("sync method end");
        return result;
    }

    @PostMapping("/async/mono")
    public Mono<String> asyncMono() {
        log.info("async method start");
        Mono<String> result = Mono.fromSupplier(this::execute);
        log.info("async method end");
        return result;
    }

    private String execute() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    }

    public record Test(String name, int age) implements Serializable {

    }
}
